package com.renrenyou.duanshipin.util;

import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class SharedPref implements ICache {

    private final MMKV mKv;

    private static final String CACHE_SP_NAME = "config";

    private SharedPref() {
        mKv = MMKV.mmkvWithID(CACHE_SP_NAME);
    }

    public static SharedPref getInstance() {
        return SingletonHolder.instance;
    }


    private static class SingletonHolder {
        private static final SharedPref instance = new SharedPref();
    }

    @Override
    public void remove(String key) {
        if (key != null) {
            mKv.removeValueForKey(key);
        }
    }

    public void clearAllExcludeKey(String... keys) {
        List<String> list = new ArrayList<>(Arrays.asList(mKv.allKeys()));
        if (keys != null) {
            Iterator<String> iterator = list.iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                for (String value : keys) {
                    if (value != null && value.equals(next)) {
                        iterator.remove();
                        break;
                    }
                }
            }
        }
        mKv.removeValuesForKeys(list.toArray(new String[0]));
    }

    @Override
    public boolean contains(String key) {
        return mKv.contains(key);
    }

    @Override
    public void clear() {
        mKv.clearAll();
    }

    public void putInt(String key, int value) {
        mKv.encode(key, value);
    }

    public int getInt(String key, int defValue) {
        return mKv.decodeInt(key, defValue);
    }


    public float getFloat(String key, int defValue) {
        return mKv.decodeFloat(key, defValue);
    }

    public void putFloat(String key, float value) {
        mKv.encode(key, value);
    }

    public void putLong(String key, Long value) {
        mKv.encode(key, value);
    }

    public long getLong(String key, long defValue) {
        return mKv.decodeLong(key, defValue);
    }


    public void putBoolean(String key, Boolean value) {
        mKv.encode(key, value);
    }

    public boolean getBoolean(String key, boolean defValue) {
        return mKv.decodeBool(key, defValue);
    }


    public void putString(String key, String value) {
        mKv.encode(key, value);
    }

    public String getString(String key, String defValue) {
        return mKv.getString(key, defValue);
    }

    @Override
    public Object get(String key) {
        return null;
    }

    @Override
    public void put(String key, Object value) {

    }
}
